<?php
/**
 * CONTENIDO extension pack (mpContenidoX), consists of multiple classes to
 * provide more features for Plugins/Modules.
 *
 * @package     mpContenidoX
 * @subpackage  Crypt
 * @author      Murat Purc <murat@purc.de>
 * @copyright   Copyright (c) 2008-2012 Murat Purc (http://www.purc.de)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html - GNU General Public License, version 2
 * @version     $Id: Base64Key.class.php 21 2012-07-16 21:33:14Z purcaholic $
 */


defined('CON_FRAMEWORK') or die('Illegal call');


/**
 * @ignore
 */
require_once('mpCrypt_Interface.class.php');


/**
 * Class to crypt data using MIME base64. Usable to obfuscate strings.
 *
 * @package     mpContenidoX
 * @subpackage  Crypt
 * @author      Murat Purc <murat@purc.de>
 */
class mpCrypt_Base64Key implements mpCrypt_Interface
{
    /**
     * The magic key
     * @var unknown_type
     */
    private $_magicKey = 'myMagicKey';


    /**
     * Constructor.
     *
     * @param   string  $key  The key for en-/decryption
     * @return  void
     */
    public function __construct($key='')
    {
        if (!empty($key)) {
            $this->setKey($key);
        }
    }


    /**
     * (non-PHPdoc)
     * @see contenido/classes/mp/mpCrypt_Interface#setKey($key)
     */
    public function setKey($key)
    {
        $key = (string) trim($key);
        if (!empty($key)) {
            $this->_magicKey = $key;
        }
    }


    /**
     * (non-PHPdoc)
     * @see contenido/classes/mp/mpCrypt_Interface#encrypt($string)
     */
    public function encrypt($string)
    {
        $result = '';
        for ($i=0; $i<strlen($string); $i++) {
            $char    = substr($string, $i, 1);
            $keychar = substr($this->_magicKey, ($i % strlen($this->_magicKey))-1, 1);
            $char    = chr(ord($char) + ord($keychar));
            $result .= $char;
        }
        return base64_encode($result);
    }


    /**
     * (non-PHPdoc)
     * @see contenido/classes/mp/mpCrypt_Interface#decrypt($string)
     */
    public function decrypt($string)
    {
        $result = '';
        $string = base64_decode($string);
        for ($i=0; $i<strlen($string); $i++) {
            $char    = substr($string, $i, 1);
            $keychar = substr($this->_magicKey, ($i % strlen($this->_magicKey))-1, 1);
            $char    = chr(ord($char) - ord($keychar));
            $result .= $char;
        }
        return $result;
    }
}
